'''
@author: Indrek Jentson
'''

from evn.models import *
from evn.importer import Importer
from django.template import Context, RequestContext
from django.shortcuts import render_to_response, redirect
from django.core.files import File
from django.contrib.auth.models import User
from evn.parsers import *
from django.utils.translation import ugettext as _

def home(request):
    if 'VN_LANG' not in request.session:
        request.session['VN_LANG'] = 'eng'
    lng = request.session.get('VN_LANG', 'eng')

    if 'VN_SELDATA' not in request.session:
        request.session['VN_SELDATA'] = 'A'
    dtype = request.session.get('VN_SELDATA', 'A')
    dtypes = [{'value':'A', 'name':_('Alphabetical list of verb classes')},
              {'value':'N', 'name':_('List of verb classes by class number')}, ]
    if request.user.is_authenticated():
        dtypes.append({'value':'M', 'name':_('List of verb classes modified by me')})

    # processing request

    if request.method == 'POST' and request.POST.has_key('lang'):
        lng = request.POST['lang']
    if request.method == 'POST' and request.POST.has_key('dtype'):
        dtype = request.POST['dtype']

    if request.method == 'POST' and request.POST.has_key('commit') and request.POST.has_key('datatype') and request.user.is_authenticated():
        if request.POST['commit'] == 'Save':
            l_datatype = request.POST['datatype']
            if l_datatype == 'language':
                l_lang = Language()
                if request.POST.has_key('value') and request.POST.has_key('name'):
                    l_lang.value = request.POST['value']
                    l_lang.name = request.POST['name']
                    l_lang.save(force_insert=True)
                
    lngs = Language.objects.all().order_by('value')

    # preparing response

    l_name = ''
    data = []
    if dtype == 'A':
        vcs = VNClass.objects.all().filter(lang__value=lng).order_by('name', '-version')
        vcs_lv = []
        if request.user.is_authenticated():
            for vc in vcs:
                if vc.name != l_name and vc.subOf == None and ((vc.status == 'A') or (vc.modified_by == request.user.username)):
                    vcs_lv.append(vc)
                l_name = vc.name
        else:
            for vc in vcs:
                if vc.name != l_name and vc.subOf == None and vc.status == 'A':
                    vcs_lv.append(vc)
                l_name = vc.name
        l_il = ' '
        l_cnt = 0
        l_cell = ''
        l_url = ''
        for vlv in vcs_lv:
            if vlv.name.upper()[0] != l_il:
                if l_cnt == 1:
                    data.append({'f_cell':l_cell, 'f_url':l_url, 's_cell':'', 's_url':''})
                    l_cnt = 0
                l_il = vlv.name.upper()[0]
                data.append({'f_cell':l_il, 'f_url':'', 's_cell':'', 's_url':''})
            if l_cnt == 0:
                l_cell = vlv.name
                if vlv.status != 'A':
                    l_cell = l_cell + ' *'
                l_url = vlv.id
                l_cnt = 1
            elif l_cnt == 1:
                l_rcell = vlv.name
                if vlv.status != 'A':
                    l_rcell = l_rcell + ' *'
                data.append({'f_cell':l_cell, 'f_url':l_url, 's_cell':l_rcell, 's_url':vlv.id})
                l_cnt = 0
        if l_cnt == 1:
            data.append({'f_cell':l_cell, 'f_url':l_url, 's_cell':'', 's_url':''})
    elif dtype == 'N':
        vcs = VNClass.objects.all().filter(lang__value=lng).order_by('nr', '-version')
        vcs_lv = []
        if request.user.is_authenticated():
            for vc in vcs:
                if vc.nr != l_name and vc.subOf == None and ((vc.status == 'A') or (vc.modified_by == request.user.username)):
                    vcs_lv.append(vc)
                l_name = vc.nr
        else:
            for vc in vcs:
                if vc.nr != l_name and vc.subOf == None and vc.status == 'A':
                    vcs_lv.append(vc)
                l_name = vc.nr

        l_cnt = len(vcs_lv) // 2
        if len(vcs_lv) % 2 == 1:
            l_cnt = l_cnt + 1
        for i in range(l_cnt):
            l_lm = ''
            l_rm = ''
            if vcs_lv[i].status != 'A':
                l_lm = ' *'
            if i + l_cnt < len(vcs_lv):
                if vcs_lv[i + l_cnt].status != 'A':
                    l_rm = ' *'
                data.append({'f_cell':vcs_lv[i].get_nr() + ' ' + vcs_lv[i].name[:vcs_lv[i].name.rfind('-')] + l_lm, 'f_url':vcs_lv[i].id,
                             's_cell':vcs_lv[i + l_cnt].get_nr() + ' ' + vcs_lv[i + l_cnt].name[:vcs_lv[i + l_cnt].name.rfind('-')] + l_rm, 's_url':vcs_lv[i + l_cnt].id})
            else:
                data.append({'f_cell':vcs_lv[i].get_nr() + ' ' + vcs_lv[i].name[:vcs_lv[i].name.rfind('-')] + l_lm, 'f_url':vcs_lv[i].id,
                             's_cell':'', 's_url':''})
    elif dtype == 'M':
        vcs = VNClass.objects.all().filter(lang__value=lng).order_by('nr', '-version')
        vcs_lv = []
        for vc in vcs:
            if vc.nr != l_name and vc.subOf == None and vc.status != 'A' and vc.modified_by == request.user.username:
                vcs_lv.append(vc)
            l_name = vc.nr

        l_cnt = len(vcs_lv) // 2
        if len(vcs_lv) % 2 == 1:
            l_cnt = l_cnt + 1
        for i in range(l_cnt):
            l_lm = ''
            l_rm = ''
            if vcs_lv[i].status != 'F':
                l_lm = ' *'
            if i + l_cnt < len(vcs_lv):
                if vcs_lv[i + l_cnt].status != 'F':
                    l_rm = ' *'
                data.append({'f_cell':vcs_lv[i].get_nr() + ' ' + vcs_lv[i].name[:vcs_lv[i].name.rfind('-')] + l_lm, 'f_url':vcs_lv[i].id,
                             's_cell':vcs_lv[i + l_cnt].get_nr() + ' ' + vcs_lv[i + l_cnt].name[:vcs_lv[i + l_cnt].name.rfind('-')] + l_rm, 's_url':vcs_lv[i + l_cnt].id})
            else:
                data.append({'f_cell':vcs_lv[i].get_nr() + ' ' + vcs_lv[i].name[:vcs_lv[i].name.rfind('-')] + l_lm, 'f_url':vcs_lv[i].id,
                             's_cell':'', 's_url':''})

    context = Context({'languages':lngs, 'sel_lang':lng, 'datatype':dtypes, 'sel_dtype':dtype, 'data':data})
    return render_to_response('home.html', context, context_instance=RequestContext(request))

def importer(request):
    imp = Importer()
    lng = request.session.get('VN_LANG', 'eng')
    if request.method == 'POST' and request.POST.has_key('lang'):
        lng = request.POST['lang']
    vnm = VNModel(lng)
    if request.method == 'POST' and request.POST.has_key('action'):
        if request.POST['action'] == 'Import':
            request.encoding = 'utf-8'
            if request.FILES.has_key('xml'):
                wf = request.FILES['xml']
                l_finished = False
                while (not l_finished):
                    if type(wf) is str and wf.upper().endswith('.XML'):
                        imp.importFromXMLFile(wf)
                        l_finished = True
                    elif wf.name.upper().endswith('.XML'):
                        imp.importFromXMLFile(wf)
                        l_finished = True
                    elif wf.name.upper().endswith('.ZIP'):
                        if not imp.hasZipFile():
                            imp.importFromZIPFile(wf)
                        if imp.hasZipFile():
                            lf = imp.getNextFileFromZIP()
                            l_finished = lf == None
                            if not l_finished and lf.name.upper().endswith('.XML'):
                                imp.importFromXMLFile(lf)
                        else:
                            l_finished = True
                            break
                    vnm = VNModel(lng)
                    vnm.name = imp.extractId()
                    vnm.members = imp.extractMembers()
                    vnm.roles = imp.extractThemRoles()
                    vnm.frames = imp.extractFrames(vnm.name)
                    vnm.subclasses = imp.extractSubClasses()
                    if request.POST.has_key('lang'):
                        lng = request.POST['lang']
                    elif request.POST.has_key('sel_lang'):
                        lng = request.POST['sel_lang']
                    vnm.lang = lng
                    vnm.setStatus('F')
                    vnm.inc_version(vnm.version, vnm.status)
                    vnm.is_modified = True
                    vnm.modified_by = request.user.username
                    res = vnm.save()
                    print 'Saving ', vnm.name, vnm.version
                    if not res['success']:
                        imp.m_status = 'Error'
                        imp.m_message = imp.m_message + ';' + res['msg']

    l = Language.objects.all().order_by('value')
    request.session['VN_LANG'] = lng
    context = Context({'ID':vnm.name, 'sel_lang':lng, 'status':imp.m_status, 'errmsg':imp.m_message, 'languages':l })
    return render_to_response('import.html', context, context_instance=RequestContext(request))

def exporter(request):
    return

def about(request):
    l_vncs = VNClass.objects.all()
    for l_vnc in l_vncs:
        l_vnc.status = 'A'
        l_vnc.save()
    context = Context({})
    return render_to_response('about.html', context, context_instance=RequestContext(request))

def getPOSTStr(p_r, p_id):
    s = ''
    if p_r.POST.has_key(p_id):
        s = p_r.POST[p_id]
    return s
                        
def getPOSTInt(p_r, p_id, p_def = None):
    s = getPOSTStr(p_r, p_id)
    try:
        if s and len(s) > 0:
            return int(s)
        else:
            return p_def
    except ValueError:
        return p_def

def data(request):
    if 'VN_LANG' not in request.session:
        request.session['VN_LANG'] = 'eng'
    lng = request.session.get('VN_LANG', 'eng')
    l_status = ''
    l_message = ''
    l_change = False
    l_delete = False
    if request.method == 'GET' and request.GET.has_key('id'):
        l_id = request.GET['id']
    if request.method == 'POST' and request.POST.has_key('id'):
        l_id = request.POST['id']
    if l_id:
        l_last = VNClass.objects.get(id=l_id)
        l_vcl = VNModel(l_last.lang.value, l_last.name)
        l_vcl.load(VNClass.decode(l_last.version))
    else:
        l_vcl = VNModel(lng, '?')
        l_vcl.setStatus('N')
        l_vcl.modified_by = request.user.username
        l_vcl.is_modified = True

    if request.method == 'POST' and request.POST.has_key('commit') and request.POST.has_key('datatype') and request.user.is_authenticated():
        if request.POST['commit'] == 'Save':
            l_datatype = request.POST['datatype']
            if l_datatype == 'vnclass':
                if request.POST.has_key('vnc_prefix'):
                    if request.POST['vnc_prefix'] + '-' + request.POST['vnc_number'] != l_vcl.name and len(request.POST['vnc_prefix']) > 0:
                        l_vcl.name = request.POST['vnc_prefix'] + '-' + request.POST['vnc_number']
                        l_change = True
            if l_datatype == 'member':
                l_member_id = getPOSTInt(request, 'member_id', -1)
                print l_member_id
                print l_vcl.members
                l_i = 0
                if l_member_id != -1: # existing member
                    while l_vcl.members[l_i]['id'] != l_member_id and l_i < len(l_vcl.members):
                        l_i = l_i + 1
                else: # new member
                    l_mem = Member().json()
                    l_vcl.members.append(l_mem)
                    l_member_id = len(l_vcl.members)-1
                if l_i < len(l_vcl.members):
                    if l_vcl.members[l_i]['name'] != getPOSTStr(request, 'name'):
                        l_vcl.members[l_i]['name'] = getPOSTStr(request, 'name')
                        l_change = True
                    if l_vcl.members[l_i]['wn'] != getPOSTStr(request, 'wn'):
                        l_vcl.members[l_i]['wn'] = getPOSTStr(request, 'wn')
                        l_change = True
                    if l_vcl.members[l_i]['locwn'] != getPOSTStr(request, 'locwn'):
                        l_vcl.members[l_i]['locwn'] = getPOSTStr(request, 'locwn')
                        l_change = True
                    if l_vcl.members[l_i]['grouping'] != getPOSTStr(request, 'grouping'):
                        l_vcl.members[l_i]['grouping'] = getPOSTStr(request, 'grouping')
                        l_change = True
                        print l_vcl.members[l_i]
            if l_datatype == 'role':
                l_role_id = getPOSTInt(request, 'role_id', -1)
                print l_role_id
                print l_vcl.roles
                l_i = 0
                if l_role_id != -1: # existing role
                    while l_vcl.roles[l_i]['id'] != l_role_id and l_i < len(l_vcl.roles):
                        l_i = l_i + 1
                else: # new role
                    l_rol = ThematicRole().json()
                    l_vcl.roles.append(l_rol)
                    l_role_id = len(l_vcl.roles)-1
                if l_i < len(l_vcl.roles):
                    if l_vcl.roles[l_i]['role'] != getPOSTStr(request, 'role'):
                        l_vcl.roles[l_i]['role'] = getPOSTStr(request, 'role')
                        l_change = True
                    if l_vcl.roles[l_i]['pos'] != getPOSTStr(request, 'position'):
                        l_vcl.roles[l_i]['pos'] = getPOSTStr(request, 'position')
                        l_change = True
                    l_rst = getPOSTStr(request, 'role_restr') 
                    if l_rst != l_vcl.roles[l_i]['restrs']:
                        l_parser = ExpressionParser(l_rst)
                        l_vcl.roles[l_i]['restrs'] = l_parser.json()
                        l_change = True
            if l_datatype == 'frame':
                l_frame_id = getPOSTInt(request, 'frame_id', -1)
                print l_frame_id
                print l_vcl.frames
                l_i = 0
                if l_frame_id != -1: # existing frame
                    while l_vcl.frames[l_i]['id'] != l_frame_id and l_i < len(l_vcl.frames):
                        l_i = l_i + 1
                else: # new frame
                    l_frm = Frame().json()
                    l_vcl.frames.append(l_frm)
                    l_i = len(l_vcl.frames)-1
                    # print l_i
                if l_i < len(l_vcl.frames):
                    if l_vcl.frames[l_i]['primary'] != getPOSTStr(request, 'primary'):
                        l_vcl.frames[l_i]['primary'] = getPOSTStr(request, 'primary')
                        l_change = True
                    if l_vcl.frames[l_i]['secondary'] != getPOSTStr(request, 'secondary'):
                        l_vcl.frames[l_i]['secondary'] = getPOSTStr(request, 'secondary')
                        l_change = True
                    if l_vcl.frames[l_i]['descriptionNumber'] != getPOSTStr(request, 'descriptionNumber'):
                        l_vcl.frames[l_i]['descriptionNumber'] = getPOSTStr(request, 'descriptionNumber')
                        l_change = True
                    if l_vcl.frames[l_i]['xtag'] != getPOSTStr(request, 'xtag'):
                        l_vcl.frames[l_i]['xtag'] = getPOSTStr(request, 'xtag')
                        l_change = True
                    if l_vcl.frames[l_i]['example'] != getPOSTStr(request, 'example'):
                        l_vcl.frames[l_i]['example'] = getPOSTStr(request, 'example')
                        l_change = True
                        
        if request.POST['commit'] == 'Delete':
            l_datatype = request.POST['datatype']
            if l_datatype == 'vnclass':
                l_delete = True
            if l_datatype == 'member':
                l_member_id = getPOSTInt(request, 'member_id', -1)
                l_i = 0
                if l_member_id != -1: # existing member
                    while l_vcl.members[l_i]['id'] != l_member_id and l_i < len(l_vcl.members):
                        l_i = l_i + 1
                    if l_i < len(l_vcl.members):
                        l_mem = l_vcl.members.pop(l_i)
                        print 'Removed member: ', l_mem
                        l_change = True
            if l_datatype == 'role':
                l_role_id = getPOSTInt(request, 'role_id', -1)
                l_i = 0
                if l_role_id != -1: # existing member
                    while l_vcl.roles[l_i]['id'] != l_role_id and l_i < len(l_vcl.roles):
                        l_i = l_i + 1
                    if l_i < len(l_vcl.roles):
                        l_rol = l_vcl.roles.pop(l_i)
                        print 'Removed role: ', l_rol
                        l_change = True
            if l_datatype == 'frame':
                l_frame_id = getPOSTInt(request, 'frame_id', -1)
                l_i = 0
                if l_frame_id != -1: # existing member
                    while l_vcl.frames[l_i]['id'] != l_frame_id and l_i < len(l_vcl.frames):
                        l_i = l_i + 1
                    if l_i < len(l_vcl.frames):
                        l_frm = l_vcl.frames.pop(l_i)
                        print 'Removed frame: ', l_frm
                        l_change = True
    if l_vcl:
        if l_change:
            l_vcl.setStatus('M')
            l_vcl.modified_by = request.user.username
            l_vcl.is_modified = True
            res = l_vcl.save()
            if res['success'] == False:
                l_status = 'Error'
                l_message = res['msg']
            l_id = l_vcl.getId()
        if l_delete and l_datatype == 'vnclass':
            VNClass.objects.get(id=l_id).delete()
            return redirect('home')

        l_roles = ThematicRoleType.getRoleSelectionList()
        context = Context({'id':l_id, 'cls':l_vcl.json(), 'status':l_status, 'errmsg':l_message, 'roles':l_roles})
        print context['cls']['frames']
    else:
        context = Context({})
    return render_to_response('data.html', context, context_instance=RequestContext(request))

def scanxsd(request):
    imp = Importer()
    cid = ''
    prdx = []
    lng = request.session.get('VN_LANG', 'eng')
    if request.method == 'POST' and request.POST.has_key('lang'):
        lng = request.POST['lang']
    if request.method == 'POST' and request.POST.has_key('action'):
        if request.POST['action'] == _('Import xsd data'):
            request.encoding = 'utf-8'
            if request.FILES.has_key('xsd'):
                wf = request.FILES['xsd']
                imp.importFromXSDFile(wf)
                prd = imp.extractTypes("predType")
                i = 0
                row = []
                for p in prd:
                    try:
                        pt = PredicateType.objects.get(value=p)
                    except PredicateType.DoesNotExist:
                        pt = PredicateType(value=p)
                        pt.save()
                    row.append(p)
                    i = i + 1
                    if i % 10 == 0:
                        prdx.append(row)
                        row = []
                if request.POST.has_key('lang'):
                    lng = request.POST['lang']
                elif request.POST.has_key('sel_lang'):
                    lng = request.POST['sel_lang']
    print prdx
    l = Language.objects.all()
    request.session['VN_LANG'] = lng
    context = Context({'ID':cid, 'sel_lang':lng, 'status':imp.m_status, 'errmsg':imp.m_message, 'languages':l, 'predicates':prdx })
    return render_to_response('scanxsd.html', context, context_instance=RequestContext(request))

